# 创建时间：2025/5/4 星期日 20:19
# 创建人：李德才


""" 如果不加限制，在类中的属性是可以随意更改的 """


class Person:
    name = ""
    age = 0

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def say_hello(self):
        print("Hello, my name is {} and I am {} years old.".format(self.name, self.age))


p = Person('John', 30)
print(p.name)
print(p.age)
p.name = "cdc"
p.age = 23
print(p.name)
print(p.age)
print("===============================================================================")


class Person2:

    def get_name(self):
        return self._name

    def set_name(self, value):
        self._name = value

    def get_age(self):
        return self._age

    def set_age(self, value):
        """ 这样就可以增加对年轻的限制"""
        if value < 0 or value > 150:
            raise ValueError("Age cannot be negative")
        self._age = value

    def __init__(self, name, age):
        self._name = name
        self._age = age

    def say_hello(self):
        print("Hello, my name is {} and I am {} years old.".format(self.name, self.age))


p2 = Person2('John', 30)
print(p2.get_name())
print(p2.get_age())
p2.set_name("cdc")
p2.set_age(80)
print(p2.get_name())
print(p2.get_age())
print("===============================================================================")


class Person3:
    def __init__(self, name, age):
        self._name = name
        self._age = age

    @property
    def age(self):  # 这样就可以像访问属性一样访问方法，但是不能修改属性的值
        return self._age

    @age.setter
    def age(self, value):  # 这样就可以像修改属性一样修改方法的值
        """ 这样就可以增加对年轻的限制"""
        if value < 0 or value > 150:
            raise ValueError("Age cannot be negative")
        self._age = value

    @property
    def name(self):
        return self._name

    @name.setter  #
    def name(self, value):
        self._name = value

    def say_hello(self):
        print("Hello, my name is {} and I am {} years old.".format(self.name, self.age))


p3 = Person3('John', 30)
print(p3.name)
print(p3.age)
p3.name = "cdc"
p3.age = 90
print(p3.name)
print(p3.age)
